package api

import (
	"fmt"
	"github.com/gin-contrib/pprof"
	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
	"github.com/yejingxuan/accumulate/application"
	"github.com/yejingxuan/accumulate/infrastructure/config"
	"github.com/yejingxuan/accumulate/interface/handler"
	"github.com/yejingxuan/accumulate/interface/middleware"
	"net/http"
)

//启动http-server
func SetupHttpServer(stockApp application.StockAppInterface) error {
	engine, err := initHttpServer(stockApp)
	if err != nil {
		return err
	}
	if err := engine.Run(fmt.Sprintf(":%d", config.CoreConf.Server.Port)); err != nil {
		return err
	}
	return nil
}

//初始化http接口
func initHttpServer(stockApp application.StockAppInterface) (*gin.Engine, error) {
	// 初始化接口层实例
	stockHandler := handler.NewStockHandler(stockApp)

	//gin.SetMode(gin.ReleaseMode)
	gin.SetMode(gin.DebugMode)
	router := gin.New()
	//跨域支持
	router.Use(middleware.Cors())
	//swagger支持
	router.GET("/accumulate/v1/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
	//性能监控
	pprof.Register(router)

	/*fs := &assetfs.AssetFS{
		Asset:     asset.Asset,
		AssetDir:  asset.AssetDir,
		AssetInfo: asset.AssetInfo,
		Prefix:    "web",
	}
	router.StaticFS("/index", fs)*/

	router.Static("/web", "./web")
	router.StaticFS("/index", http.Dir("web"))

	//信息获取
	apiInfo := router.Group("/accumulate/v1/info")
	{
		apiInfo.POST("/stock/query", stockHandler.QueryStockPage) //查询stock信息
		apiInfo.POST("/stock/follow", stockHandler.Follow)        //stock关注状态
		apiInfo.GET("/stock/:code", stockHandler.GetStockInfo)    //获取详情
		apiInfo.GET("/tags", stockHandler.GetStockTags)           //获取标签
		apiInfo.POST("/stock/comment", stockHandler.Comment)      //评论
	}

	//任务执行
	apiExec := router.Group("/accumulate/v1/exec")
	{
		apiExec.POST("/update/stock", stockHandler.UpdateStock)         //更新stock基本数据
		apiExec.POST("/update/kline", stockHandler.UpdateKline)         //更新kline数据
		apiExec.GET("/update/kline/process", stockHandler.KlineProcess) //更新kline数据
		apiExec.POST("/analyse", stockHandler.AnalyseInfo)              //数据分析计算
	}

	return router, nil
}
